/// 路径工具函数
pub mod path {
    
    /// 规范化路径，防止目录遍历攻击
    pub fn normalize_path(path: &str) -> String {
        let path = path.trim_start_matches('/');
        if path.is_empty() {
            "/".to_string()
        } else {
            format!("/{}", path)
        }
    }
    
    /// 检查路径是否安全（防止目录遍历）
    pub fn is_safe_path(path: &str) -> bool {
        !path.contains("..") && !path.contains("//")
    }
    
    /// 将虚拟路径转换为实际文件系统路径
    pub fn virtual_to_real_path(virtual_path: &str, home_dir: &str) -> String {
        let normalized = normalize_path(virtual_path);
        if normalized == "/" {
            home_dir.to_string()
        } else {
            format!("{}{}", home_dir, normalized)
        }
    }
}

/// 网络工具函数
pub mod network {
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};
    
    /// 解析PORT命令的地址
    pub fn parse_port_command(port_str: &str) -> Option<SocketAddr> {
        let parts: Vec<&str> = port_str.split(',').collect();
        if parts.len() != 6 {
            return None;
        }
        
        let ip_parts: Result<Vec<u8>, _> = parts[0..4]
            .iter()
            .map(|s| s.parse::<u8>())
            .collect();
        
        let port_parts: Result<Vec<u16>, _> = parts[4..6]
            .iter()
            .map(|s| s.parse::<u16>())
            .collect();
        
        match (ip_parts, port_parts) {
            (Ok(ip_bytes), Ok(port_bytes)) => {
                if ip_bytes.len() == 4 && port_bytes.len() == 2 {
                    let ip = Ipv4Addr::new(ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3]);
                    let port = (port_bytes[0] << 8) | port_bytes[1];
                    Some(SocketAddr::new(IpAddr::V4(ip), port))
                } else {
                    None
                }
            }
            _ => None,
        }
    }
    
    /// 格式化PORT命令响应
    pub fn format_port_response(addr: SocketAddr) -> String {
        match addr.ip() {
            IpAddr::V4(ipv4) => {
                let port = addr.port();
                format!("PORT {},{},{},{},{},{}",
                    ipv4.octets()[0],
                    ipv4.octets()[1],
                    ipv4.octets()[2],
                    ipv4.octets()[3],
                    port >> 8,
                    port & 0xFF
                )
            }
            IpAddr::V6(_) => {
                // IPv6 not supported in traditional PORT command
                "".to_string()
            }
        }
    }
}

/// 字符串工具函数
pub mod string {
    /// 移除字符串末尾的换行符
    pub fn trim_newline(s: &str) -> &str {
        s.trim_end_matches('\n').trim_end_matches('\r')
    }
    
    /// 检查字符串是否为有效的文件名
    pub fn is_valid_filename(filename: &str) -> bool {
        !filename.is_empty()
            && !filename.contains('/')
            && !filename.contains('\\')
            && !filename.contains('\0')
            && filename.len() <= 255
    }
}
